package com.blb.controller;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.Scanner;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.blb.utils.UUIDUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class FileUploadServlet{

    private static String filePath = "D:/file_upload/";

    /**
     * 上传文件
     * @param files
     * @return
     * @throws IllegalStateException
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("upload")
    public String upload(@RequestParam("file") MultipartFile[] files) throws IllegalStateException, IOException{
        StringBuffer sb = new StringBuffer();
        for (int i =0; i<files.length; i++) {
            MultipartFile file = files[i];
            String filename = file.getOriginalFilename();
            String newFileName = UUIDUtils.getID() + filename.substring(filename.lastIndexOf("."));
            file.transferTo(new File(filePath + newFileName));

            sb.append(newFileName);
            if (i!=files.length-1) {
                sb.append(",");
            }

        }
        return "{\"name\" : \""+sb.toString()+"\"}";
    }
}
